package com.giveu.signature.common.util;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
//import org.apache.poi.xwpf.converter.core.BasicURIResolver;
//import org.apache.poi.xwpf.converter.core.FileImageExtractor;
//import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
//import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

import com.giveu.common.utils.security.Base64;

import fr.opensagres.poi.xwpf.converter.core.BasicURIResolver;
import fr.opensagres.poi.xwpf.converter.core.FileImageExtractor;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.List;
public class DocToHtml {
	public static void main(String argv[]) {
		try {
			String content=wordToHtml("D:\\test.docx");
			System.out.println(content);
			String content1=docxToHtml2("D:\\test.docx");
			//			System.out.println(content1);
			//			        	convert2Html("D://test.docx","D://test.html");
		} catch (Exception e) {
			e.printStackTrace();
		}        	     
	}   
	public static String wordToHtml(String filePath) throws Exception{
		if(filePath.endsWith(".doc")){
			String content=convert2Html(filePath);
			return content;
		}
		if(filePath.endsWith(".docx")){
			String content=docxToHtml(filePath);
			return content;
		}
		return null;
	}
	//docx转html
	//生成html文件
	//输出html标签和内容
	public static String docxToHtml(String sourceFileName) throws Exception {
		String htmlPath=sourceFileName.substring(0,sourceFileName.indexOf("."))+".html";
		XWPFDocument document = new XWPFDocument(new FileInputStream(sourceFileName));
		XHTMLOptions options = XHTMLOptions.create().indent(4);
		File outFile = new File(htmlPath);
		outFile.getParentFile().mkdirs();
		OutputStream out = new FileOutputStream(outFile);
		XHTMLConverter.getInstance().convert(document,out, options);		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		XHTMLConverter.getInstance().convert(document, baos, options); 				
		baos.close();
		String content =new String(baos.toByteArray());
		//替换UEditor无法识别的转义字符
		String htmlContent1=content.replaceAll("&ldquo;","\"").replaceAll("&rdquo;","\"").replaceAll("&mdash;","-");
		return htmlContent1;    	
	}
	//doc 转 html 
	public static String convert2Html(String fileName)
			throws TransformerException, IOException,
			ParserConfigurationException {

		HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(fileName));//WordToHtmlUtils.loadDoc(new FileInputStream(inputFile));
		//兼容2007 以上版本
		WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
				DocumentBuilderFactory.newInstance().newDocumentBuilder()
				.newDocument());
		wordToHtmlConverter.processDocument(wordDocument);
		//解析html
		Document htmlDocument = wordToHtmlConverter.getDocument();      
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		DOMSource domSource = new DOMSource(htmlDocument);      
		StreamResult streamResult = new StreamResult(out);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = tf.newTransformer();    
		serializer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "HTML");
		serializer.transform(domSource, streamResult);
		out.close();
		String htmlContent=new String(out.toByteArray());
		//替换UEditor无法识别的转义字符
		String htmlContent1=htmlContent.replaceAll("&ldquo;","\"").replaceAll("&rdquo;","\"").replaceAll("&mdash;","-");       
		return htmlContent1;
	}

	public static void writeFile(String content, String path) {
		FileOutputStream fos = null;
		BufferedWriter bw = null;
		try {
			File file = new File(path);
			fos = new FileOutputStream(file);
			bw = new BufferedWriter(new OutputStreamWriter(fos,"GB2312"));
			bw.write(content);
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			try {
				if (bw != null)
					bw.close();
				if (fos != null)
					fos.close();
			} catch (IOException ie) {
			}
		}
	}

	public static void convert2Html(String fileName, String outPutFile)
			throws TransformerException, IOException,
			ParserConfigurationException {
		HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(fileName));//WordToHtmlUtils.loadDoc(new FileInputStream(inputFile));
		WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
				DocumentBuilderFactory.newInstance().newDocumentBuilder()
				.newDocument());
		wordToHtmlConverter.setPicturesManager( new PicturesManager() {
			public String savePicture(byte[] content,
					PictureType pictureType, String suggestedName,
					float widthInches, float heightInches )
			{
				return "test/"+suggestedName;
			}
		} );
		wordToHtmlConverter.processDocument(wordDocument);
		//save pictures
		List pics=wordDocument.getPicturesTable().getAllPictures();
		if(pics!=null){
			for(int i=0;i<pics.size();i++){
				Picture pic = (Picture)pics.get(i);
				System.out.println();
				try {
					pic.writeImageContent(new FileOutputStream("D:/test/"
							+ pic.suggestFullFileName()));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}  
			}
		}
		Document htmlDocument = wordToHtmlConverter.getDocument();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		DOMSource domSource = new DOMSource(htmlDocument);
		StreamResult streamResult = new StreamResult(out);

		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = tf.newTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);
		out.close();
		writeFile(new String(out.toByteArray()), outPutFile);
	}

	//docx转换html
	public static String docxToHtml2(String fileName) throws IOException {
		XWPFDocument docxDocument = new XWPFDocument(new FileInputStream(fileName));
		// 配置
		XHTMLOptions options = XHTMLOptions.create();
		// 设置图片存储路径
		String path = System.getProperty("java.io.tmpdir");
		String firstImagePathStr = path + "/" + String.valueOf(System.currentTimeMillis());
		options.setExtractor(new FileImageExtractor(new File(firstImagePathStr)));
		options.URIResolver(new BasicURIResolver(firstImagePathStr));
		// 转换html
		ByteArrayOutputStream htmlStream = new ByteArrayOutputStream();
		XHTMLConverter.getInstance().convert(docxDocument, htmlStream, options);
		String htmlStr = htmlStream.toString();
		// 将image文件转换为base64并替换到html字符串里 
		String middleImageDirStr = "/word/media";
		String imageDirStr = firstImagePathStr + middleImageDirStr;
		File imageDir = new File(imageDirStr);
		String[] imageList = imageDir.list();
		if (imageList != null) {
			for (int i = 0; i < imageList.length; i++) {
				String oneImagePathStr = imageDirStr + "/" + imageList[i];
				File oneImageFile = new File(oneImagePathStr);
				String imageBase64Str = new String(Base64.decode(FileUtils.readFileToByteArray(oneImageFile)), "UTF-8");
				htmlStr = htmlStr.replace(oneImagePathStr, "data:image/png;base64," + imageBase64Str);
			}
		}
		//删除图片路径
		File firstImagePath = new File(firstImagePathStr);
		FileUtils.deleteDirectory(firstImagePath);
		System.out.println(htmlStr);
		return htmlStr;

	}}
